package com.gf.snoopy.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.gf.snoopy.domain.Project;
import com.gf.snoopy.domain.SubProject;
import com.gf.snoopy.dto.ProjectDto;
import com.gf.snoopy.mapper.ProjectMapper;
import com.gf.snoopy.platform.exception.PokeErrorCode;
import com.gf.snoopy.platform.exception.PokeException;
import com.gf.snoopy.util.ConvertUtil;
import com.gf.snoopy.util.page.Page;
import com.gf.snoopy.util.page.PagedList;
import com.gf.snoopy.util.page.PaginationUtil;

@Service
public class ProjectService {
	
	private Logger logger = Logger.getLogger(getClass());
	
	@Resource
	private ProjectMapper projectMapper;
	
	@Resource
	private SubProjectService subProjectService;
	
	/**
	 * 新增记录
	 * @param data
	 * @throws PokeException
	 */
	public void save(ProjectDto data) throws PokeException{
		Project convert = ConvertUtil.convert(data, Project.class);
		if(convert==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"project数据出错");
		}
		projectMapper.insert(convert);
	}
	
	/**
	 * 更新记录
	 * @param data
	 * @throws PokeException
	 */
	public void update(ProjectDto data) throws PokeException{
		Project convert = ConvertUtil.convert(data, Project.class);
		if(convert==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"project数据出错");
		}
		projectMapper.updateByPrimaryKeySelective(convert);
	}
	
	/**
	 * 查找结果
	 * @param id
	 * @return
	 * @throws PokeException
	 */
	public ProjectDto findById(Integer id) throws PokeException{
		if(id==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"查询的projectId为空");
		}
		Project project = projectMapper.selectByPrimaryKey(id);
		return convertProjectDto(project);
	}
	
	/**
	 * 根据Id删除记录
	 * @param id
	 * @throws PokeException
	 */
	public void deleteById(Integer id) throws PokeException{
		if(id==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"查询的projectId为空");
		}
		projectMapper.deleteByPrimaryKey(id);
		subProjectService.deleteByPorjectId(id);
	}
	
	/**
	 * 分页查询
	 * @param query
	 * @param page
	 * @return
	 * @throws PokeException
	 */
	public PagedList<ProjectDto> getProjectPage(ProjectDto query,Page page) throws PokeException{
		if(query==null||page==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"查询参数错误");
		}
		final Project dbQuery = ConvertUtil.convert(query,Project.class);
		PagedList<Project> voteInCondition =  PaginationUtil.pagedQuery(page, new Callable<List<Project>>() {            
            public List<Project> call() throws Exception {
                return projectMapper.queryByCondition(dbQuery);
            }
        });
		
		return new PagedList<ProjectDto>(voteInCondition.getPage(),
				convertToProjectDtoList(voteInCondition.getList()));
	}
	
	private List<ProjectDto> convertToProjectDtoList(List<Project> projects) throws PokeException{
		List<ProjectDto> dtos = new ArrayList<ProjectDto>();
		if(CollectionUtils.isNotEmpty(projects)){
			for(Project project:projects){
				dtos.add(convertProjectDto(project));
			}
		}
		return dtos;
	}
	
	private ProjectDto convertProjectDto(Project project) throws PokeException{
		if(project==null){
			return null;
		}
		ProjectDto dto = ConvertUtil.convert(project, ProjectDto.class);
		
		Long total = 0l;
		dto.setExchangeName(project.getExchange().getName());
		if(CollectionUtils.isNotEmpty(project.getSubprojects())){
			for(SubProject subProject:project.getSubprojects()){
				if(StringUtils.isNotBlank(subProject.getCollect())){
					try{
						total = total + Long.valueOf(subProject.getCollect());
					}catch(Exception e){
						logger.error(e.getMessage(),e);
						throw new PokeException(PokeErrorCode.INVALID_PARAM,project.getName()+"的子项目存在非法的发行量数据");
					}
				}
			}
		}
		dto.setTotalCollect(total);
		return dto;
	}
}
